//
//  OrderRecordViewController.swift
//  koolcar
//
//  Created by kuaimaxiansheng on 2023/11/1.
//

import UIKit
import MJRefresh

class OrderRecordViewController: BaseViewController {
    var emptyView: LYEmptyView!
    var tableView: BaseTableView!
    var dataArray = NSMutableArray()
    var pageNumber: NSInteger = 1
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = Theme.F5Color
        self.navBar.title = MMLocalizedString("order_record", comment: "订单记录")
        self.initTableView()
        self.requestUsedcarOrderList(isMore: false, hudFlag: false)
    }
    
    func initTableView(){
        self.tableView = BaseTableView(frame: CGRect(x: 0, y: NavBarHight, width: kScreenWidth, height: kScreenHeight - TabbarHeight), style: .grouped)
        self.tableView.register(OrderRecordTableViewCell.self, forCellReuseIdentifier: "OrderRecordTableViewCell")
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.backgroundColor = Theme.viewBkgGrayColor
        self.tableView.separatorStyle = .none
        self.tableView.rowHeight = UITableViewAutomaticDimension
        self.tableView.estimatedRowHeight = 165
        self.view.addSubview(tableView)
        self.setUpNoData()
        self.addPullRefreash()
        self.addLoadMoreRefreash()
    }
  
    ///空视图
    func setUpNoData() {
        self.emptyView = LYEmptyView.emptyActionView(withImageStr: "icon_empty", titleStr: MMLocalizedString("no_data", comment: "暂无数据"), detailStr: "", btnTitleStr: "") {
        }
        emptyView.titleStr = ""
        emptyView?.subViewMargin = 28
        emptyView?.contentViewOffset = 0
        emptyView.isHidden = true
        self.tableView.ly_emptyView = self.emptyView
    }

    ///空视图
    func willShowEmptyView() {
        if self.dataArray.count == 0 {
            self.tableView.mj_footer?.isHidden = true
            self.emptyView.isHidden = false
            self.emptyView?.titleStr = MMLocalizedString("no_data", comment: "暂无数据")
        }else{
            self.emptyView.isHidden = true
            self.emptyView?.titleStr = ""
        }
    }
    
    
    
    
    /*
     * 添加头部刷新
     */
    func addPullRefreash()  {
 
        self.tableView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: { [weak self] in
            self?.pageNumber = 1
            self?.requestUsedcarOrderList(isMore: false, hudFlag: false)
        })
    }
    
    
    //MARK: -  底部刷新
    func addLoadMoreRefreash()  {
        let footer = MJRefreshBackNormalFooter.init(refreshingBlock: { [weak self] in
            self?.pageNumber = self!.pageNumber + 1
            self?.requestUsedcarOrderList(isMore: true, hudFlag: false)
    
        })
        self.tableView.mj_footer = footer
    }
    
    
    
    //MARK: - Request
    func requestUsedcarOrderList(isMore: Bool, hudFlag: Bool) {
        if hudFlag {
            self.view.showLoadingHUDText(nil)
        }
        
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.usedcarOrderList(param: ["status": "","pageNumber": "\(self.pageNumber)","pageSize":"10"]), objectType: CarOrderListModel.self) { data in
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
            self.view.handleLoading()
            let resultObj = data as! CarOrderListModel
            if resultObj.code == "1" {
                let resultContent = resultObj.data?.content
                if resultContent != nil && (resultContent?.count)! > 0  {
                    if isMore == true {
                        //加载更多
                        for itemObj in resultContent! {
                            self.dataArray.add(itemObj)
                        }
                    }else{
                        self.dataArray.removeAllObjects()
                        //刷新
                        for itemObj in resultContent! {
                            self.dataArray.add(itemObj)
                        }
                        if self.dataArray.count < 10 {
                            self.tableView.mj_footer?.isHidden = true //不够20个则隐藏底部刷新
                        }
                    }
                }else{
                    //没有数据
                    if isMore == true {
                        if self.dataArray.count > 0 {
                            self.tableView.mj_footer?.endRefreshingWithNoMoreData() //提示没有更多数据
                        }
                    }else{
                        self.dataArray.removeAllObjects()
                    }
                }
              
            }else{
                self.view.makeToastBottom(message: resultObj.msg ?? "")
                self.tableView.mj_header.endRefreshing()
            }
            self.tableView.reloadData()
            self.willShowEmptyView()
        } error: { err in
            self.willShowEmptyView()
            self.tableView.mj_header.endRefreshing()
        }
    }
   
    
    

}


extension OrderRecordViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.1
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return IphoneXMarginBottom + 34
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "OrderRecordTableViewCell", for: indexPath) as! OrderRecordTableViewCell
        if self.dataArray.count > indexPath.row {
            let model = self.dataArray[indexPath.row] as! OrderContentListModel
            cell.setModel(model: model)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if self.dataArray.count > indexPath.row {
            let model = self.dataArray[indexPath.row] as! OrderContentListModel
            if model.type == 0 || model.type == 3 {//车辆订单详情
               let vc = CarOrderDetailsViewController()
                vc.id = model.id ?? 0
                self.navigationController?.pushViewController(vc, animated: true)
            }else{//商品详情
               let vc = StoreOrderDetailsViewController()
                vc.id = model.id ?? 0
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }
    }
}
